<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>数字分合小能手</title>
    <style>
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
            -webkit-tap-highlight-color: transparent;
            touch-action: manipulation;
        }
        
        body {
            background: linear-gradient(135deg, #6ecbf5 0%, #059ee3 100%);
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 10px;
            font-family: "Comic Sans MS", "楷体", sans-serif;
        }
        
        #game-container {
            width: 100%;
            max-width: 500px;
            background-color: white;
            border-radius: 20px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
            overflow: hidden;
        }
        
        #header {
            background: linear-gradient(135deg, #4CAF50 0%, #2E7D32 100%);
            color: white;
            padding: 15px;
            text-align: center;
            position: relative;
        }
        
        #title {
            font-size: 24px;
            margin-bottom: 5px;
        }
        
        #level-info {
            font-size: 16px;
            opacity: 0.9;
        }
        
        #progress-container {
            height: 8px;
            background-color: rgba(255, 255, 255, 0.3);
            border-radius: 4px;
            margin-top: 10px;
            overflow: hidden;
        }
        
        #progress-bar {
            height: 100%;
            background-color: #FFEB3B;
            width: 0%;
            transition: width 0.3s;
        }
        
        #question-panel {
            padding: 20px 15px;
            text-align: center;
            font-size: 28px;
            background-color: #E8F5E9;
            border-bottom: 2px dashed #4CAF50;
            min-height: 80px;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        #game-area {
            display: flex;
            padding: 15px;
            min-height: 250px;
        }
        
        #known-number-container {
            flex: 1;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            margin-right: 10px;
        }
        
        #known-number-label {
            font-size: 16px;
            margin-bottom: 5px;
            color: #666;
        }
        
        #known-number {
            width: 100%;
            height: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 60px;
            color: #2196F3;
            background-color: #E3F2FD;
            border-radius: 10px;
            box-shadow: inset 0 0 10px rgba(0, 0, 0, 0.1);
        }
        
        #number-grid-container {
            flex: 2;
            display: flex;
            flex-direction: column;
        }
        
        #number-grid-label {
            font-size: 16px;
            margin-bottom: 5px;
            color: #666;
            text-align: center;
        }
        
        #number-grid {
            flex: 1;
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            grid-gap: 10px;
        }
        
        .number-btn {
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 32px;
            background-color: #FF9800;
            color: white;
            border-radius: 10px;
            cursor: pointer;
            transition: all 0.2s;
            box-shadow: 0 4px 0 #E65100;
            user-select: none;
        }
        
        .number-btn:active {
            transform: translateY(4px);
            box-shadow: 0 0 0 #E65100;
        }
        
        #level-select {
            display: flex;
            justify-content: center;
            padding: 10px;
            background-color: #F5F5F5;
            border-top: 1px solid #E0E0E0;
        }
        
        .level-btn {
            padding: 8px 20px;
            margin: 0 10px;
            background-color: #9C27B0;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
        }
        
        .level-btn.active {
            background-color: #7B1FA2;
            box-shadow: inset 0 2px 5px rgba(0,0,0,0.2);
        }
        
        #control-panel {
            padding: 15px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            background-color: #F5F5F5;
            border-top: 1px solid #E0E0E0;
        }
        
        #score {
            font-size: 20px;
            color: #FF5722;
            font-weight: bold;
        }
        
        #audio-controls {
            display: flex;
            gap: 10px;
        }
        
        .control-btn {
            padding: 8px 15px;
            background-color: #2196F3;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
        }
        
        #feedback {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            font-size: 60px;
            font-weight: bold;
            opacity: 0;
            transition: opacity 0.3s, transform 0.3s;
            z-index: 100;
            text-shadow: 2px 2px 4px rgba(0,0,0,0.5);
            pointer-events: none;
        }
        
        #good-feedback {
            color: #4CAF50;
            display: none;
        }
        
        #bad-feedback {
            color: #F44336;
            display: none;
        }
        
        #game-over {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.7);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 200;
            display: none;
        }
        
        #game-over-content {
            background-color: white;
            padding: 30px;
            border-radius: 15px;
            text-align: center;
            max-width: 80%;
        }
        
        #final-score {
            font-size: 24px;
            margin: 15px 0;
            color: #FF5722;
        }
        
        #restart-game {
            padding: 10px 20px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
            margin-top: 15px;
        }
        
        #audio-init-message {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.8);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 300;
            color: white;
            text-align: center;
            padding: 20px;
        }
        
        #init-audio-btn {
            padding: 15px 30px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 10px;
            cursor: pointer;
            font-size: 18px;
            margin-top: 20px;
        }
        
        #wechat-tip {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.9);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 400;
            color: white;
            text-align: center;
            padding: 20px;
        }
        
        #wechat-tip-content {
            background-color: white;
            color: #333;
            padding: 30px;
            border-radius: 15px;
            max-width: 80%;
        }
        
        #open-in-browser {
            padding: 10px 20px;
            background-color: #2196F3;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
            margin-top: 15px;
        }
        
        @media (max-width: 480px) {
            #game-area {
                flex-direction: column;
                min-height: 350px;
            }
            
            #known-number-container {
                margin-right: 0;
                margin-bottom: 10px;
                min-height: 80px;
            }
            
            .number-btn {
                font-size: 28px;
                min-height: 70px;
            }
            
            #question-panel {
                font-size: 24px;
                padding: 15px 10px;
            }
            
            #audio-controls {
                flex-direction: column;
                gap: 5px;
            }
        }
    </style>
</head>
<body>
    <!-- 微信提示 -->
    <div id="wechat-tip">
        <div id="wechat-tip-content">
            <h2>温馨提示</h2>
            <p>检测到您在微信中浏览本游戏</p>
            <p>为了获得最佳体验（特别是语音功能），请点击右上角菜单，选择"在浏览器打开"</p>
            <button id="open-in-browser">知道了</button>
        </div>
    </div>

    <!-- 音频初始化提示 -->
    <div id="audio-init-message">
        <div>
            <h2>欢迎来到数字分合小游戏！</h2>
            <p>为了获得最佳游戏体验，请点击下方按钮初始化音频系统</p>
            <button id="init-audio-btn">初始化音频并开始游戏</button>
        </div>
    </div>

    <div id="game-container">
        <div id="header">
            <div id="title">数字分合小能手</div>
            <div id="level-info">第一关: 数字分解 (2可以分成...)</div>
            <div id="progress-container">
                <div id="progress-bar"></div>
            </div>
        </div>
        
        <div id="question-panel">2可以分成...</div>
        
        <div id="game-area">
            <div id="known-number-container">
                <div id="known-number-label">已知数字</div>
                <div id="known-number">1</div>
            </div>
            <div id="number-grid-container">
                <div id="number-grid-label">点击正确数字</div>
                <div id="number-grid">
                    <!-- 数字按钮将由JavaScript动态生成 -->
                </div>
            </div>
        </div>
        
        <div id="level-select">
            <button id="level1-btn" class="level-btn active">第一关：分解</button>
            <button id="level2-btn" class="level-btn">第二关：合成</button>
        </div>
        
        <div id="control-panel">
            <div id="score">得分: 0</div>
            <div id="audio-controls">
                <button id="music-toggle" class="control-btn">背景音乐: 开</button>
                <button id="sound-toggle" class="control-btn">音效: 开</button>
                <button id="tts-toggle" class="control-btn">题目朗读: 开</button>
                <button id="reset-btn" class="control-btn">重新开始</button>
            </div>
        </div>
    </div>
    
    <div id="feedback">
        <div id="good-feedback">Good!</div>
        <div id="bad-feedback">再试试!</div>
    </div>
    
    <div id="game-over">
        <div id="game-over-content">
            <h2>游戏结束</h2>
            <p id="final-score">您的最终得分: 0</p>
            <button id="restart-game">再玩一次</button>
        </div>
    </div>

    <!-- 音频元素 -->
    <audio id="bgMusic" loop preload="auto">
        <!-- 使用免费的背景音乐资源 -->
        <source src="https://assets.mixkit.co/music/preview/mixkit-kids-game-idea-28.mp3" type="audio/mpeg">
    </audio>
    <audio id="correctSound" preload="auto">
        <!-- 使用免费的正确音效 -->
        <source src="https://assets.mixkit.co/sfx/preview/mixkit-correct-answer-tone-2870.mp3" type="audio/mpeg">
    </audio>
    <audio id="wrongSound" preload="auto">
        <!-- 使用免费的错误音效 -->
        <source src="https://assets.mixkit.co/sfx/preview/mixkit-wrong-answer-fail-notification-946.mp3" type="audio/mpeg">
    </audio>

    <script>
        // 游戏状态
        const gameState = {
            currentLevel: 1,
            currentNumber: 2,
            knownPart: 1,
            score: 0,
            musicEnabled: true,
            soundEnabled: true,
            ttsEnabled: true, // 题目朗读功能
            progress: 0,
            questionCount: 0,
            maxQuestions: 15,
            gameActive: true,
            audioInitialized: false,
            isWeChat: false
        };

        // 音频元素
        const bgMusic = document.getElementById('bgMusic');
        const correctSound = document.getElementById('correctSound');
        const wrongSound = document.getElementById('wrongSound');
        
        // 检测是否在微信中打开
        function detectWeChat() {
            const ua = window.navigator.userAgent.toLowerCase();
            if (ua.indexOf('micromessenger') !== -1) {
                gameState.isWeChat = true;
                document.getElementById('wechat-tip').style.display = 'flex';
            }
        }
        
        // 初始化音频系统
        function initAudioSystem() {
            // 设置音频音量
            bgMusic.volume = 0.3;
            correctSound.volume = 0.7;
            wrongSound.volume = 0.7;
            
            // 预加载音频（静音）
            bgMusic.muted = true;
            correctSound.muted = true;
            wrongSound.muted = true;
            
            // 尝试播放并立即暂停以预加载
            const audioElements = [bgMusic, correctSound, wrongSound];
            
            audioElements.forEach(audio => {
                audio.play().then(() => {
                    audio.pause();
                    audio.currentTime = 0;
                }).catch(e => {
                    console.log("音频预加载失败:", e);
                });
            });
            
            // 隐藏初始化消息
            document.getElementById('audio-init-message').style.display = 'none';
            gameState.audioInitialized = true;
            
            // 开始背景音乐（取消静音）
            setTimeout(() => {
                bgMusic.muted = false;
                if (gameState.musicEnabled) {
                    bgMusic.play().catch(e => {
                        console.log("背景音乐播放失败，等待用户交互");
                    });
                }
            }, 500);
        }
        
        // 语音朗读功能
        function speakText(text) {
            if (!gameState.ttsEnabled || !gameState.audioInitialized) return;
            
            // 检查浏览器是否支持语音合成
            if ('speechSynthesis' in window) {
                // 创建语音合成实例[1](@ref)
                const utterance = new SpeechSynthesisUtterance(text);
                
                // 设置语音参数[2](@ref)
                utterance.lang = 'zh-CN'; // 使用中文
                utterance.rate = 0.9; // 稍慢的语速，适合小学生
                utterance.pitch = 1.0;
                utterance.volume = 1.0;
                
                // 尝试选择中文语音[3](@ref)
                const voices = speechSynthesis.getVoices();
                const chineseVoice = voices.find(voice => 
                    voice.lang.includes('zh') || voice.lang.includes('CN')
                );
                
                if (chineseVoice) {
                    utterance.voice = chineseVoice;
                }
                
                // 播放语音[5](@ref)
                speechSynthesis.speak(utterance);
                
                // 监听语音结束事件[2](@ref)
                utterance.onend = function() {
                    console.log('题目朗读完毕');
                };
                
                utterance.onerror = function(event) {
                    console.error('语音朗读出错:', event.error);
                };
            } else {
                console.log('您的浏览器不支持语音朗读功能');
            }
        }
        
        // 初始化游戏
        function initGame() {
            detectWeChat();
            initNumberGrid();
            generateQuestion();
            updateProgressBar();
            
            // 添加按钮事件监听
            document.getElementById('reset-btn').addEventListener('click', resetGame);
            document.getElementById('music-toggle').addEventListener('click', toggleMusic);
            document.getElementById('sound-toggle').addEventListener('click', toggleSound);
            document.getElementById('tts-toggle').addEventListener('click', toggleTTS);
            document.getElementById('level1-btn').addEventListener('click', () => switchLevel(1));
            document.getElementById('level2-btn').addEventListener('click', () => switchLevel(2));
            document.getElementById('restart-game').addEventListener('click', restartGame);
            document.getElementById('init-audio-btn').addEventListener('click', initAudioSystem);
            document.getElementById('open-in-browser').addEventListener('click', function() {
                document.getElementById('wechat-tip').style.display = 'none';
            });
            
            // 添加全局点击事件来初始化音频
            document.addEventListener('click', function initAudioOnInteraction() {
                if (!gameState.audioInitialized) {
                    initAudioSystem();
                }
                document.removeEventListener('click', initAudioOnInteraction);
            });
        }

        // 初始化数字网格
        function initNumberGrid() {
            const grid = document.getElementById('number-grid');
            grid.innerHTML = '';
            
            for (let i = 1; i <= 9; i++) {
                const numBtn = document.createElement('div');
                numBtn.className = 'number-btn';
                numBtn.textContent = i;
                // 同时绑定touchstart和click事件，确保移动端兼容性
                numBtn.addEventListener('touchstart', function(e) {
                    e.preventDefault();
                    if (gameState.gameActive && gameState.audioInitialized) checkAnswer(i);
                });
                numBtn.addEventListener('click', function() {
                    if (gameState.gameActive && gameState.audioInitialized) checkAnswer(i);
                });
                grid.appendChild(numBtn);
            }
        }

        // 生成题目
        function generateQuestion() {
            const questionPanel = document.getElementById('question-panel');
            const knownNumber = document.getElementById('known-number');
            
            if (gameState.currentLevel === 1) {
                // 第一关：数字分解
                questionPanel.textContent = `${gameState.currentNumber}可以分成...`;
                knownNumber.textContent = gameState.knownPart;
                document.getElementById('level-info').textContent = `第一关: 数字分解 (${gameState.currentNumber}可以分成...)`;
                
                // 朗读题目
                setTimeout(() => {
                    speakText(`${gameState.currentNumber}可以分成${gameState.knownPart}和几？`);
                }, 300);
            } else {
                // 第二关：数字合成
                questionPanel.textContent = `${gameState.knownPart}和几合成${gameState.currentNumber}?`;
                knownNumber.textContent = gameState.knownPart;
                document.getElementById('level-info').textContent = `第二关: 数字合成 (${gameState.questionCount+1}/${gameState.maxQuestions})`;
                
                // 朗读题目
                setTimeout(() => {
                    speakText(`${gameState.knownPart}和几合成${gameState.currentNumber}？`);
                }, 300);
            }
            
            updateProgressBar();
        }

        // 检查答案
        function checkAnswer(selectedNumber) {
            if (!gameState.gameActive || !gameState.audioInitialized) return;
            
            let correctAnswer;
            
            if (gameState.currentLevel === 1) {
                // 第一关：已知数字分解，求另一个部分
                correctAnswer = gameState.currentNumber - gameState.knownPart;
            } else {
                // 第二关：已知一个部分和总和，求另一个部分
                correctAnswer = gameState.currentNumber - gameState.knownPart;
                gameState.questionCount++;
            }
            
            if (selectedNumber === correctAnswer) {
                // 回答正确
                gameState.score += 10;
                document.getElementById('score').textContent = `得分: ${gameState.score}`;
                
                if (gameState.soundEnabled) {
                    // 播放正确音效
                    correctSound.currentTime = 0;
                    correctSound.play().catch(e => console.log("正确音效播放失败:", e));
                    
                    // 朗读"正确"
                    if (gameState.ttsEnabled) {
                        setTimeout(() => {
                            speakText("正确");
                        }, 200);
                    }
                }
                
                showFeedback(true);
            } else {
                // 回答错误
                gameState.score = Math.max(0, gameState.score - 10); // 确保分数不为负
                document.getElementById('score').textContent = `得分: ${gameState.score}`;
                
                if (gameState.soundEnabled) {
                    wrongSound.currentTime = 0;
                    wrongSound.play().catch(e => console.log("错误音效播放失败:", e));
                    
                    // 朗读"再试试"
                    if (gameState.ttsEnabled) {
                        setTimeout(() => {
                            speakText("再试试");
                        }, 200);
                    }
                }
                
                showFeedback(false);
            }
            
            // 延迟1秒后进入下一题或结束游戏
            setTimeout(() => {
                if (gameState.currentLevel === 1) {
                    // 第一关逻辑
                    gameState.knownPart++;
                    if (gameState.knownPart > gameState.currentNumber - 1) {
                        gameState.currentNumber++;
                        gameState.knownPart = 1;
                    }
                    
                    // 检查第一关是否结束（完成9可以分成8和1后）
                    if (gameState.currentNumber > 9 || (gameState.currentNumber === 9 && gameState.knownPart > 8)) {
                        endGame();
                        return;
                    }
                } else {
                    // 第二关逻辑
                    // 检查第二关是否结束（完成15道题后）
                    if (gameState.questionCount >= gameState.maxQuestions) {
                        endGame();
                        return;
                    }
                    
                    // 生成新的随机题目
                    const target = Math.floor(Math.random() * 8) + 2; // 2-10之间的随机数
                    gameState.currentNumber = target;
                    gameState.knownPart = Math.floor(Math.random() * (target - 1)) + 1; // 1到target-1的随机数
                }
                
                generateQuestion();
                updateProgressBar();
            }, 1000);
        }

        // 显示反馈动画
        function showFeedback(isCorrect) {
            const feedback = document.getElementById('feedback');
            const goodFeedback = document.getElementById('good-feedback');
            const badFeedback = document.getElementById('bad-feedback');
            
            if (isCorrect) {
                goodFeedback.style.display = 'block';
                badFeedback.style.display = 'none';
            } else {
                goodFeedback.style.display = 'none';
                badFeedback.style.display = 'block';
            }
            
            feedback.style.opacity = '1';
            feedback.style.transform = 'translate(-50%, -60%)';
            
            setTimeout(() => {
                feedback.style.opacity = '0';
                feedback.style.transform = 'translate(-50%, -50%)';
            }, 1000);
        }

        // 更新进度条
        function updateProgressBar() {
            let progressPercent;
            
            if (gameState.currentLevel === 1) {
                // 第一关进度：基于当前数字和已知部分
                const totalCombinations = 36; // 2到9的所有分解组合总数
                let completedCombinations = 0;
                
                // 计算已完成的组合数
                for (let i = 2; i < gameState.currentNumber; i++) {
                    completedCombinations += (i - 1);
                }
                completedCombinations += (gameState.knownPart - 1);
                
                progressPercent = (completedCombinations / totalCombinations) * 100;
            } else {
                // 第二关进度：基于题目数量
                progressPercent = (gameState.questionCount / gameState.maxQuestions) * 100;
            }
            
            document.getElementById('progress-bar').style.width = `${progressPercent}%`;
        }

        // 切换关卡
        function switchLevel(level) {
            if (!gameState.gameActive) return;
            
            gameState.currentLevel = level;
            gameState.currentNumber = 2;
            gameState.knownPart = 1;
            gameState.questionCount = 0;
            gameState.progress = 0;
            
            // 更新界面
            document.getElementById('level1-btn').classList.toggle('active', level === 1);
            document.getElementById('level2-btn').classList.toggle('active', level === 2);
            
            generateQuestion();
            updateProgressBar();
        }

        // 重置游戏
        function resetGame() {
            gameState.score = 0;
            gameState.progress = 0;
            gameState.questionCount = 0;
            gameState.gameActive = true;
            document.getElementById('score').textContent = `得分: ${gameState.score}`;
            document.getElementById('game-over').style.display = 'none';
            
            if (gameState.currentLevel === 1) {
                gameState.currentNumber = 2;
                gameState.knownPart = 1;
            } else {
                // 生成新的随机题目
                const target = Math.floor(Math.random() * 8) + 2;
                gameState.currentNumber = target;
                gameState.knownPart = Math.floor(Math.random() * (target - 1)) + 1;
            }
            
            generateQuestion();
            updateProgressBar();
        }

        // 结束游戏
        function endGame() {
            gameState.gameActive = false;
            document.getElementById('final-score').textContent = `您的最终得分: ${gameState.score}`;
            document.getElementById('game-over').style.display = 'flex';
            
            // 朗读结束语
            if (gameState.ttsEnabled) {
                setTimeout(() => {
                    speakText(`游戏结束，您的得分是${gameState.score}分`);
                }, 1000);
            }
        }

        // 重新开始游戏
        function restartGame() {
            resetGame();
        }

        // 切换背景音乐
        function toggleMusic() {
            gameState.musicEnabled = !gameState.musicEnabled;
            const button = document.getElementById('music-toggle');
            
            if (gameState.musicEnabled) {
                button.textContent = "背景音乐: 开";
                bgMusic.play().catch(e => console.log("音乐播放失败:", e));
            } else {
                button.textContent = "背景音乐: 关";
                bgMusic.pause();
            }
        }

        // 切换音效
        function toggleSound() {
            gameState.soundEnabled = !gameState.soundEnabled;
            const button = document.getElementById('sound-toggle');
            button.textContent = gameState.soundEnabled ? "音效: 开" : "音效: 关";
        }
        
        // 切换题目朗读
        function toggleTTS() {
            gameState.ttsEnabled = !gameState.ttsEnabled;
            const button = document.getElementById('tts-toggle');
            button.textContent = gameState.ttsEnabled ? "题目朗读: 开" : "题目朗读: 关";
        }

        // 页面加载完成后初始化游戏
        window.addEventListener('DOMContentLoaded', initGame);
    </script>
</body>
</html>